package com.zuoban.controller;

import com.alibaba.cloud.ai.dashscope.api.DashScopeApi;
import com.alibaba.cloud.ai.dashscope.chat.DashScopeChatOptions;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.ai.chat.model.ChatModel;
import org.springframework.ai.chat.model.ChatResponse;
import org.springframework.ai.chat.prompt.Prompt;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Flux;

@RestController
public class ChatModelController {


    private final ChatModel chatModel;
    public ChatModelController(ChatModel chatModel) {
        this.chatModel = chatModel;
    }


    @GetMapping("/simple/chat")
    public String simpleChat() {
        return chatModel.call("hi");
    }

    @GetMapping("chat-stream")
    public Flux<String> chatStream(HttpServletResponse response) {
        response.setCharacterEncoding("UTF-8");

        Flux<ChatResponse> stream = chatModel.stream(new Prompt("hi", DashScopeChatOptions
                .builder()
                .withModel(DashScopeApi.ChatModel.QWEN_PLUS.getModel())
                .build()));
        return stream.mapNotNull(resp -> resp.getResult().getOutput().getText());
    }
}
